<template>
  <el-dialog v-model="visible" :title="title" width="50%">
    <el-form :model="form">
      <el-form-item label="姓名" :label-width="formLabelWidth">
        <el-input v-model="form.userName" />
      </el-form-item>
      <el-form-item label="手机号" :label-width="formLabelWidth">
        <el-input v-model="form.phone" />
      </el-form-item>
      <el-form-item label="单位名称" :label-width="formLabelWidth">
        <el-input v-model="form.unitName" />
      </el-form-item>
      <el-form-item label="单位职务" :label-width="formLabelWidth">
        <el-input v-model="form.unitPosition" />
      </el-form-item>
      <el-form-item label="头像" :label-width="formLabelWidth">
        <el-upload
          class="avatar-uploader"
          action="http://localhost:8080/rbac/common/upload"
          :headers="headers"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
        >
          <img
            v-if="form.avatar"
            :src="imgSrc"
            class="avatar"
            style="width: 100px; height: 100px;"
          />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="身份" :label-width="formLabelWidth">
        <el-select v-model="form.status" placeholder="请选择身份">
          <el-option label="游客" :value="0" />
          <el-option label="会员单位成员" :value="1" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { computed, ref } from "vue";
import { ElMessage } from "element-plus";
import { Plus } from "@element-plus/icons-vue"; // 引入 Plus 图标
import type ResultType from "../../../type/ResultType.ts";
import {instance} from "../request.js";

const visible = ref(false)
const formLabelWidth = '140px'
const title = ref('新增')
//上传相关
let headers = {
  token:sessionStorage.getItem('token')
}

// 表单默认值
let defaultForm = {
  id: '',
  userName: '',
  phone: '',
  unitName: '',
  unitPosition: '',
  status: 0,
  avatar:'',
}

let form = ref(defaultForm)

// 重置表单
function resetForm() {
  form.value = structuredClone(defaultForm)
}

// 根据id查询数据
async function getById(id: string) {
  try {
    let result: ResultType = await instance.get('/bsWxUser/' + id)
    let { code, data, msg } = result.data
    if (code == 200) {
      return data
    }
    ElMessage({ message: msg, type: 'warning', })
  } catch (e) {
    console.log(e)
    ElMessage({ message: '查询数据失败', type: 'warning', })
  }
}

// 声明需要监听的父组件事件
const emit = defineEmits(['refresh'])

// 提交表单
async function submitForm() {
  //判断是新增还是编辑
  try {
    let result: ResultType
    if (form.value.id) {
      result = await instance.put('/bsWxUser/'+ form.value.id, form.value)
    }else{
      result = await instance.post('/bsWxUser', form.value)
    }
    let { code, msg } = result.data
    if (code == 200) {
      ElMessage({ message: msg, type: 'success', })
      visible.value = false
      emit('refresh')
      return
    }
    ElMessage({ message: msg, type: 'warning', })
  } catch (e) {
    console.log(e)
    ElMessage({ message: '保存/更新数据失败', type: 'warning', })
  }
}

// add方法
function add() {
  resetForm()
  title.value = '新增'
  visible.value = true
}

// 编辑的方法
async function edit(row: any) {
  title.value = '编辑'
  visible.value = true
  form.value = await getById(row.id)
}

// 处理头像上传成功
function handleAvatarSuccess(response: any, uploadFile: any) {
  if (response.code === 200) {
    form.value.avatar = response.data; // 假设后端返回图片路径
    ElMessage({ message: "头像上传成功", type: "success" });
  } else {
    ElMessage({ message: "头像上传失败", type: "warning" });
  }
}

let imgSrc = computed(() => {
  //判断是否http/https开头
  if (form.value.avatar.startsWith('http://') || form.value.avatar.startsWith('https://')) {
    return form.value.avatar;
  }
  return form.value.avatar ? 'http://localhost:8080/rbac/common/download/' + form.value.avatar : '';
});

// 暴露给外面使用
defineExpose({
  add,
  edit,
})
</script>

<style lang="scss" scoped>
.avatar-uploader .el-upload {
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
  border: 1px dashed #ccc;
}
</style>